# encoding: utf-8
"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '28/05/2024'
    comment: 用户意图相关逻辑
"""
import re
from datetime import datetime
import asyncio
from project.model.basic import User
from project.lib.common import get_redis
from project.service.agents.agent import Agent

# setting
agent_profile = "你是如味堂的服务小妹，你叫小呦，性感妖娆，说话声音甜美，是个小萝莉，you speak like 林志玲，懂的讨客人欢心。"
user_role = "客人"

knowledge_global = {}

class MerchantService:
    """
    """
    @staticmethod
    def get_rick_text(dev_id):
        """ 取得富文本
        :return:
        """
        rds = get_redis()
        key = f'rick_text_{dev_id}'
        rich_text = rds.get(key)

        return rich_text

    @staticmethod
    async def load_knowledge(dev_id, rich_text):
        prompt = f"""
        这是一段富文本，请去除HTML标签后，处理为分好段的文本。
        {rich_text}
        """
        response = knowledge_global.get(dev_id)
        if response:
            return response

        user = User()
        agent = Agent(user, business_name='rick版')
        response = await agent.async_interact(prompt=prompt)
        knowledge_global[dev_id] = response

        return response

    @staticmethod
    async def chat_streaming(dev_id, user_message):
        """ 对话(流式)
        :return:
        """
        user = User(dev_id=dev_id)
        agent = Agent(user, user_message=user_message, memories_key='merchant', business_name='rick版聊天')
        # 添加用户记忆
        agent.add_user_memories(datetime.now().strftime("%m/%d/%Y %H:%M:%S") + user_role + " 对你说: " + user_message)
        user_memories = agent.load_user_memories(count=1000)


        rick_text = MerchantService.get_rick_text(dev_id)
        knowledge = await MerchantService.load_knowledge(dev_id, rick_text)

        instruction = agent_profile \
                      + "\n 你脑海里的知识有：" + str(knowledge) \
                      + "\n 你的历史记忆如下：" + str(user_memories) \
                      + '\n 目前与你对话的人对你说：' + user_message \
                      + "\n 和你对话的对方是：" + user_role \
                      + " \n 你接下来会对对方说（注意只返回你会说的话，没有其他内容或者语气假设或者旁白）："
        response = await agent.async_interact_streaming(prompt=instruction)

        return response

    @staticmethod
    async def get_rich_text_url(dev_id, user_message):
        """ 得到富文本连接
        :param user_message:
        :return:
        """
        user = User(dev_id=dev_id)
        agent = Agent(user, user_message=user_message, memories_key='merchant', business_name='rick版聊天')
        # 添加用户记忆
        # agent.add_user_memories(datetime.now().strftime("%m/%d/%Y %H:%M:%S") + user_role + " 对你说: " + user_message)
        user_memories = agent.load_user_memories(count=1000)

        rick_text = MerchantService.get_rick_text(dev_id)

        knowledge = await MerchantService.load_knowledge(dev_id, rick_text)

        instruction = agent_profile \
                      + "\n 你脑海里的知识库有：" + str(knowledge) \
                      + "\n 你的历史记忆如下：" + str(user_memories) \
                      + '\n 目前与你对话的人对你说：' + user_message \
                      + "\n 和你对话的对方是：" + user_role \
                      + "\n 你的任务：请你判断当前应该展示什么图片或表格或其他展示性信息，所有信息都以URL形式存在。返回可以在浏览器打开的Url格式，URL你只能从你的知识库里取，不能自己杜撰！！！必须从你知识库里返回一个。\n " \
                        "错误返回举例：" \
                        "错例1：根据对话内容，陈总希望听《大闹天宫》的故事。基于你提供的知识库，可以为陈总提供《大闹天宫》第一章的图片链接。因此，当前应该返回的URL资源是：<https://www.baidu.com/1.jpg> " \
                        "\n错误原因：加了很多描述，没有直接返回url链接。" \
                        "\n正确返回：https://www.baidu.com/1.jpg" \
                        "\n ###Output:"

        response = await agent.async_interact(prompt=instruction)
        # # 添加用户记忆
        # agent.add_user_memories(datetime.now().strftime("%m/%d/%Y %H:%M:%S") + f" 你向{user_role}说: " + user_message)
        # if url == 'none' or not url:
        #     url = ''

        # 使用findall方法找到所有匹配的URL
        url = response
        if response:
            # 正则表达式匹配URL模式
            url_pattern = re.compile(r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+')
            urls = url_pattern.findall(response)
            url = urls[0] if urls else ''

        return url


if __name__ == "__main__":
    pass
    user = User()
    rich_text = """
        <p><span class="ql-size-huge">大闹天宫</span></p><p><br></p><p>第一章 孙大圣缘起花果山</p><p>话分两头，孙行者拜别老师傅。</p><p><br></p><p><br></p><p><br></p><p><strong>第二章 行者一怒上九霄</strong></p><p>说话间，十万天兵灰飞烟灭，怎叫一个惨惨惨。</p><p><br></p><p><img src="https://roboland-deliv.ubtrobot.com/vision/richtext/20241128/d82489cb2c7ad58e8a07c8a5afed6b9f.jpg"></p><p><strong>第三章 佛祖</strong></p><p><strong>佛祖哈哈哈哈</strong></p>
        """
    asyncio.run(MerchantService.load_knowledge(user, rich_text))
    print(knowledge)
